import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export const useTable = (config) => {
  const tableData = ref([])
  const total = ref(0)
  const loading = ref(false)
  const pageInfo = reactive({
    pageNum: 1,
    pageSize: 10
  })

  watch(() => pageInfo.pageNum, () => {
    methods.getList()
  })

  watch(() => pageInfo.pageSize, () => {
    pageInfo.pageNum = 1
    methods.getList()
  })

  onMounted(() => {
    methods.getList()
  })

  const methods = {
    getList: async (params={}) => {
      loading.value = true
      setTimeout(async () => {
        try {
          const res = await config?.getDataApi({...params, ...pageInfo})
          tableData.value = res.list || []
          total.value = res.total || 0
        } catch (err) {
          
        } finally {
          loading.value = false
        }
      }, 300)
    },

    handleDelete: (params) => {
      ElMessageBox.confirm(
        '是否确认删除此内容？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(async () => {
          await config?.deleteApi(params)
          ElMessage.success('删除成功')
          methods.getList()
        })
        .catch(() => {})
    }
  }

  return {
    tableData,
    total,
    loading,
    pageInfo,
    methods,
  }
}